package com.kk.shiro;

import com.kk.config.SpringContextBean;
import com.kk.model.Permission;
import com.kk.model.Role;
import com.kk.model.User;
import com.kk.repository.UserRepository;
import com.kk.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;

public class MyShiroRelam extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;

    /**
     * @param principals
     * @return Authorization：授权
     * 授权访问控制:只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("用户权限配置。。。。。。。。。。");
        //访问@RequirePermission注解的url时触发
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User userInfo = (User) principals.getPrimaryPrincipal();
        //获得用户的角色，及权限进行绑定
        for (Role role : userInfo.getRoles()) {
            authorizationInfo.addRole(role.getName());
            for (Permission p : role.getPermissions()) {
                authorizationInfo.addStringPermission(p.getPermission());
            }
        }
        return authorizationInfo;
    }

    /**
     * @param auth
     * @return
     * @throws AuthenticationException Authentication：身份验证，认证
     *                                 用于验证用户身份:默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        if (this.userRepository == null) {
            this.userRepository = SpringContextBean.getBean(this.userRepository.getClass());
        }
        System.out.println("验证用户登录信息");
        String username = (String) auth.getPrincipal();
        System.out.println("登录用户名： " + username);
        String token = (String) auth.getCredentials();
        System.out.println("token=" + auth.getCredentials());
        String userId = JwtUtil.getUserId(token);
        if (userId == null) {
            throw new UnauthorizedException("token invalid");
        }
        Optional<User> user = this.userRepository.findById(userId);
        if (user == null || !user.isPresent()) {
            throw new UnauthorizedException("User didn't existed!");
        }
        if (!JwtUtil.verify(token, userId, user.get().getPassword())) {
            throw new UnauthorizedException("Username or password error");
        }
        return new SimpleAuthenticationInfo(token, token, this.getName());
//        //从数据库查询出User信息及用户关联的角色，权限信息，以备权限分配时使用
//        User user = userService.findUserByName(username);
//        if (null == user) return null;
//        System.out.println("username: " + user.getUsername() + " ; password : " + user.getPassword());
//        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
//                user, //用户名
//                user.getPassword(), //密码
//                getName()  //realm name
//        );
//        return authenticationInfo;
    }
}
